package com.fiberhome.opticalbox.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.BaseFragment;
import com.fiberhome.opticalbox.C;
import com.fiberhome.opticalbox.net.NetConstant;
import com.fiberhome.opticalbox.net.NetManager.TcpErrorListener;
import com.fiberhome.opticalbox.net.NetManager.TcpListener;
import com.fiberhome.opticalbox.net.bean.Parameter;
import com.fiberhome.opticalbox.net.bean.Parameter.WifiSSIDList;
import com.fiberhome.opticalbox.net.utils.JsonUtil;
import com.fiberhome.opticalbox.ui.ProductListActivity;
import com.fiberhome.opticalbox.view.TitleView;
import com.fiberhome.opticalbox.view.third.xlist.XListView;
import com.fiberhome.opticalbox.view.third.xlist.XListView.IXListViewListener;

public class SurfSettingsFragment extends BaseFragment {

	private TitleView titleView;
	private View layWired, layWireless;
	private RadioButton rbWired, rbWireless;
	// wired part
	private View layFlagPppoe, layFlagStaticIp, layFlagDhcp, layPartPppoe, layPartStaticIp, layPartDhcp;
	private EditText edPppoeName, edPppoePwd, edIp, edSubnetMask, edGateWay, edDNS1, edDNS2;
	private View layWrapPppoeName, layWrapPppoePwd, layWrapIp, layWrapSubnetMask, layWrapGateWay, layWrapDNS1, layWrapDNS2;

	// wireless part
	private XListView listView;
	private List<WifiSSIDList> wifiInfoList = new ArrayList<WifiSSIDList>();

	public static final int SURF_WAY_WIRD_PPPOE = 0;
	public static final int SURF_WAY_WIRD_STATIC_IP = 1;
	public static final int SURF_WAY_WIRD_DHCP = 2;

	private Parameter wiredParameter;
	private int currentSurfWirdWay = SURF_WAY_WIRD_PPPOE;

	private Dialog dlgWirelessConnect, dlgLoading;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		registerChildTcpListener(tcpListener);
		registerChildTcpErrorListener(tcpErrorListener);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ob_fragment_surf_settings, null);

		titleView = (TitleView) view.findViewById(R.id.ob_titleView);
		titleView.setTitle(R.string.ob_surf_settings_1);
		titleView.setBackground(R.drawable.ob_bg_title);
		titleView.addLeftDrawableMenu(holder, R.drawable.ob_ico_back, 15, 25, onMainBackClickListener);

		view.findViewById(R.id.btn_submit).setOnClickListener(onSubmitClickListener);
		rbWireless = (RadioButton) view.findViewById(R.id.rb_wireless);
		rbWireless.setOnClickListener(onSurfWayClickListener);
		rbWired = (RadioButton) view.findViewById(R.id.rb_wired);
		rbWired.setOnClickListener(onSurfWayClickListener);

		layWireless = view.findViewById(R.id.lay_content_wireless);
		layWired = view.findViewById(R.id.lay_content_wired);

		// wireless
		listView = (XListView) layWireless.findViewById(R.id.ob_listView);
		listView.setAdapter(wifiInfoAdapter);

		listView.setOnItemClickListener(onItemClickListener);
		listView.setPullLoadEnable(false);
		listView.setPullRefreshEnable(true);
		listView.setXListViewListener(listViewListener);
		// test
		wifiInfoList.add(new WifiSSIDList("ssid", "power", "encr", "conn"));
		wifiInfoList.add(new WifiSSIDList("ssid", "power", "encr", "conn"));
		wifiInfoList.add(new WifiSSIDList("ssid", "power", "encr", "conn"));
		wifiInfoList.add(new WifiSSIDList("ssid", "power", "encr", "conn"));
		// wired
		layWired.findViewById(R.id.lay_pppoe).setOnClickListener(onWirdWayClickListener);
		layWired.findViewById(R.id.lay_static_ip).setOnClickListener(onWirdWayClickListener);
		layWired.findViewById(R.id.lay_dhcp).setOnClickListener(onWirdWayClickListener);
		layFlagPppoe = layWired.findViewById(R.id.lay_pppoe_flag);
		layFlagStaticIp = layWired.findViewById(R.id.lay_static_ip_flag);
		layFlagDhcp = layWired.findViewById(R.id.lay_dhcp_flag);
		layPartPppoe = layWired.findViewById(R.id.lay_part_pppoe);
		layPartStaticIp = layWired.findViewById(R.id.lay_part_static_ip);
		layPartDhcp = layWired.findViewById(R.id.lay_part_dhcp);
		edPppoeName = (EditText) layWired.findViewById(R.id.ed_pppoe_name);
		edPppoePwd = (EditText) layWired.findViewById(R.id.ed_pppoe_pwd);
		edIp = (EditText) layWired.findViewById(R.id.ed_ip);
		edSubnetMask = (EditText) layWired.findViewById(R.id.ed_subnet_mask);
		edGateWay = (EditText) layWired.findViewById(R.id.ed_gateway);
		edDNS1 = (EditText) layWired.findViewById(R.id.ed_dns_1);
		edDNS2 = (EditText) layWired.findViewById(R.id.ed_dns_2);
		layWrapPppoeName = layWired.findViewById(R.id.lay_wrap_pppoe_name);
		layWrapPppoePwd = layWired.findViewById(R.id.lay_wrap_pppoe_pwd);
		layWrapIp = layWired.findViewById(R.id.lay_wrap_ip);
		layWrapSubnetMask = layWired.findViewById(R.id.lay_wrap_subnet_mask);
		layWrapGateWay = layWired.findViewById(R.id.lay_wrap_gateway);
		layWrapDNS1 = layWired.findViewById(R.id.lay_wrap_dns_1);
		layWrapDNS2 = layWired.findViewById(R.id.lay_wrap_dns_2);

		edPppoeName.setOnFocusChangeListener(onEditTextFocusChangeListener);
		edPppoePwd.setOnFocusChangeListener(onEditTextFocusChangeListener);
		edIp.setOnFocusChangeListener(onEditTextFocusChangeListener);
		edSubnetMask.setOnFocusChangeListener(onEditTextFocusChangeListener);
		edGateWay.setOnFocusChangeListener(onEditTextFocusChangeListener);
		edDNS1.setOnFocusChangeListener(onEditTextFocusChangeListener);
		edDNS2.setOnFocusChangeListener(onEditTextFocusChangeListener);

		requestGetWiredInfo();
		requestGetWirelessInfo();
		return view;
	}

	private IXListViewListener listViewListener = new IXListViewListener() {
		@Override
		public void onRefresh() {
			requestGetWirelessInfo();
		}

		@Override
		public void onLoadMore() {
			listView.stopLoadMore();
		}
	};

	private void requestGetWirelessInfo() {
		String WifiIndex = "1";
		netManager.sendTcp(JsonUtil.get_GET_WIFI_SSIDLIST(WifiIndex));
	}

	private void requestGetWiredInfo() {
		String WANName = "";
		netManager.sendTcp(JsonUtil.get_QUERY_WAN_INFO(WANName));
	}

	private void requestWirelessConnect(String SSID, String PWD, String ENCRYPT) {
		String WifiIndex = "1";
		String SSIDIndex = "1";
		String Enable = "1";
		String WifiCmdMode = "1";
		String PowerLevel = ""; //
		String Channel = ""; //
		String Hidden = "";
		netManager.sendTcp(JsonUtil.get_SET_WIFI_INFO(WifiIndex, SSIDIndex, SSID, PWD, ENCRYPT, PowerLevel, Channel, Enable, WifiCmdMode, Hidden));
	}

	private void requestWiredConnect(Parameter wiredParameter) {
		netManager.sendTcp(JsonUtil.get_SET_ROUTE_WAN_INFO(wiredParameter));
	}

	private TcpListener tcpListener = new TcpListener() {

		@Override
		public void onReceive(String cmdType, Parameter param) {
			if (NetConstant.QUERY_WAN_INFO.equals(cmdType)) {
				wiredParameter = param;
				if ("0".equals(param.UPLINKMODE)) {
					rbWired.performClick();
					if ("PPPoE".equals(param.ADDRESSTYPE)) {
						layWired.findViewById(R.id.lay_pppoe).performClick();
						edPppoeName.setText(param.PPPOE_USR_NAME != null ? param.PPPOE_USR_NAME : "");
						edPppoePwd.setText(param.PPPOE_PASSWORD != null ? param.PPPOE_PASSWORD : "");
					} else if ("Static".equals(param.ADDRESSTYPE)) {
						layWired.findViewById(R.id.lay_static_ip).performClick();
						edIp.setText(param.IPADDRESS != null ? param.IPADDRESS : "");
						edSubnetMask.setText(param.SUBNETMASK != null ? param.SUBNETMASK : "");
						edGateWay.setText(param.GATEWAY != null ? param.GATEWAY : "");
						edDNS1.setText(param.DNS1 != null ? param.DNS1 : "");
						edDNS2.setText(param.DNS2 != null ? param.DNS2 : "");
					} else if ("DHCP".equals(param.ADDRESSTYPE)) {
						layWired.findViewById(R.id.lay_dhcp).performClick();
					}
				} else if ("1".equals(param.UPLINKMODE)) {
					rbWireless.performClick();
				}
			} else if (NetConstant.GET_WIFI_SSIDLIST.equals(cmdType)) {
				listView.stopRefresh();
				wifiInfoList.clear();
				wifiInfoList.addAll(param.SSIDList);
				wifiInfoAdapter.notifyDataSetChanged();
			} else if (NetConstant.SET_ROUTE_WAN_INFO.equals(cmdType)) {
				showToast(R.string.ob_success_set_wired);
				if (dlgLoading != null) {
					dlgLoading.dismiss();
				}
			} else if (NetConstant.SET_WIFI_INFO.equals(cmdType)) {
				showToast(R.string.ob_success_set_wireless);
				if (dlgLoading != null) {
					dlgLoading.dismiss();
				}
				actionStart(ProductListActivity.class);
				finishAttachActivity();
			}

		}
	};

	private TcpErrorListener tcpErrorListener = new TcpErrorListener() {
		@Override
		public void onError(String cmdType) {
			if (NetConstant.QUERY_WAN_INFO.equals(cmdType)) {
			} else if (NetConstant.GET_WIFI_SSIDLIST.equals(cmdType)) {
				listView.stopRefresh();
			} else if (NetConstant.SET_ROUTE_WAN_INFO.equals(cmdType)) {
				showToast(R.string.ob_fail_set_wired);
				if (dlgLoading != null) {
					dlgLoading.dismiss();
				}
			} else if (NetConstant.SET_WIFI_INFO.equals(cmdType)) {
				// return success ,but server disconnect, so deal as success
				showToast(R.string.ob_success_set_wireless);
				if (dlgLoading != null) {
					dlgLoading.dismiss();
				}
				actionStart(ProductListActivity.class);
				finishAttachActivity();
			}
		}
	};

	private OnClickListener onSurfWayClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			layWired.setVisibility(View.INVISIBLE);
			layWireless.setVisibility(View.INVISIBLE);
			switch (view.getId()) {
			case R.id.rb_wired:
				layWired.setVisibility(View.VISIBLE);
				break;
			case R.id.rb_wireless:
				layWireless.setVisibility(View.VISIBLE);
				break;
			}
		}
	};

	private OnClickListener onWirdWayClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			layFlagPppoe.setVisibility(View.INVISIBLE);
			layPartPppoe.setVisibility(View.INVISIBLE);
			layFlagStaticIp.setVisibility(View.INVISIBLE);
			layPartStaticIp.setVisibility(View.INVISIBLE);
			layFlagDhcp.setVisibility(View.INVISIBLE);
			layPartDhcp.setVisibility(View.INVISIBLE);
			switch (view.getId()) {
			case R.id.lay_pppoe:
				layFlagPppoe.setVisibility(View.VISIBLE);
				layPartPppoe.setVisibility(View.VISIBLE);
				currentSurfWirdWay = SURF_WAY_WIRD_PPPOE;
				break;
			case R.id.lay_static_ip:
				layFlagStaticIp.setVisibility(View.VISIBLE);
				layPartStaticIp.setVisibility(View.VISIBLE);
				currentSurfWirdWay = SURF_WAY_WIRD_STATIC_IP;
				break;
			case R.id.lay_dhcp:
				layFlagDhcp.setVisibility(View.VISIBLE);
				layPartDhcp.setVisibility(View.VISIBLE);
				currentSurfWirdWay = SURF_WAY_WIRD_DHCP;
				break;
			}
		}
	};

	private OnClickListener onSubmitClickListener = new OnClickListener() {
		String pppoeName, pppoePwd, ip, subnetMask, gateWay, dns1, dns2;

		@Override
		public void onClick(View view) {
			if (!rightParams()) {
				showToast(R.string.ob_surf_wrong_params);
				return;
			}
			wiredParameter.WANName = "nas0";
			wiredParameter.PPPOE_USR_NAME = "";
			wiredParameter.PPPOE_PASSWORD = "";
			wiredParameter.IPADDRESS = "";
			wiredParameter.SUBNETMASK = "";
			wiredParameter.GATEWAY = "";
			wiredParameter.DNS1 = "";
			wiredParameter.DNS2 = "";
			switch (currentSurfWirdWay) {
			case SURF_WAY_WIRD_PPPOE:
				wiredParameter.ADDRESSTYPE = "PPPoE";
				wiredParameter.PPPOE_USR_NAME = pppoeName;
				wiredParameter.PPPOE_PASSWORD = pppoePwd;
				break;
			case SURF_WAY_WIRD_STATIC_IP:
				wiredParameter.ADDRESSTYPE = "Static";
				wiredParameter.IPADDRESS = ip;
				wiredParameter.SUBNETMASK = subnetMask;
				wiredParameter.GATEWAY = gateWay;
				wiredParameter.DNS1 = dns1;
				wiredParameter.DNS2 = dns2;
				break;
			case SURF_WAY_WIRD_DHCP:
				wiredParameter.ADDRESSTYPE = "DHCP";
				break;
			}

			showLoadingDialog(R.string.ob_wait_set_wired);
			requestWiredConnect(wiredParameter);
		}

		private boolean rightParams() {
			int background = R.drawable.ob_border_n_ffff0000;
			boolean result = true;
			switch (currentSurfWirdWay) {
			case SURF_WAY_WIRD_PPPOE:
				pppoeName = edPppoeName.getText().toString().trim();
				pppoePwd = edPppoePwd.getText().toString().trim();
				if (TextUtils.isEmpty(pppoeName)) {
					layWrapPppoeName.setBackgroundResource(background);
					result = false;
				} else if (TextUtils.isEmpty(pppoePwd)) {
					layWrapPppoePwd.setBackgroundResource(background);
					result = false;
				}
				break;
			case SURF_WAY_WIRD_STATIC_IP:
				ip = edIp.getText().toString().trim();
				subnetMask = edSubnetMask.getText().toString().trim();
				gateWay = edGateWay.getText().toString().trim();
				dns1 = edDNS1.getText().toString().trim();
				dns2 = edDNS2.getText().toString().trim();
				if (TextUtils.isEmpty(ip) || !ip.matches(C.app.ipAddress)) {
					layWrapIp.setBackgroundResource(background);
					result = false;
				} else if (TextUtils.isEmpty(subnetMask) || !subnetMask.matches(C.app.ipAddress)) {
					layWrapSubnetMask.setBackgroundResource(background);
					result = false;
				} else if (TextUtils.isEmpty(gateWay) || !gateWay.matches(C.app.ipAddress)) {
					layWrapGateWay.setBackgroundResource(background);
					result = false;
				} else if (TextUtils.isEmpty(dns1) || !dns1.matches(C.app.ipAddress)) {
					layWrapDNS1.setBackgroundResource(background);
					result = false;
				} else if (TextUtils.isEmpty(dns2) || !dns2.matches(C.app.ipAddress)) {
					layWrapDNS2.setBackgroundResource(background);
					result = false;
				}
				break;
			}
			return result;
		}
	};

	private OnFocusChangeListener onEditTextFocusChangeListener = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View view, boolean hasFocus) {
			int background = hasFocus ? R.drawable.ob_border_n_ff00aef1 : R.drawable.ob_border_n_ffe1e1e1;
			switch (view.getId()) {
			case R.id.ed_pppoe_name:
				layWrapPppoeName.setBackgroundResource(background);
				break;
			case R.id.ed_pppoe_pwd:
				layWrapPppoePwd.setBackgroundResource(background);
				break;
			case R.id.ed_ip:
				layWrapIp.setBackgroundResource(background);
				break;
			case R.id.ed_subnet_mask:
				layWrapSubnetMask.setBackgroundResource(background);
				break;
			case R.id.ed_gateway:
				layWrapGateWay.setBackgroundResource(background);
				break;
			case R.id.ed_dns_1:
				layWrapDNS1.setBackgroundResource(background);
				break;
			case R.id.ed_dns_2:
				layWrapDNS2.setBackgroundResource(background);
				break;
			}
		}
	};

	private OnItemClickListener onItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			WifiSSIDList wifiInfo = wifiInfoList.get(position - 1);
			if (wifiInfo.isSecurity()) {
				showInputWirelessPwdDialog(wifiInfo);
			} else {
				showLoadingDialog(R.string.ob_wait_set_wifi_mode_1);
				requestWirelessConnect(wifiInfo.getSSID(), "", wifiInfo.getENCRYPT());
			}
		}
	};

	private void showInputWirelessPwdDialog(final WifiSSIDList wifiInfo) {
		View content = inflater.inflate(R.layout.ob_dialog_part_wireless_pwd, null);
		TextView txWirelessName = (TextView) content.findViewById(R.id.tx_name);
		txWirelessName.setText("Huawei-123456");
		final ImageView imgShowWirelessPwd = (ImageView) content.findViewById(R.id.img_show_wireless_pwd);
		View layShowWirelessPwd = content.findViewById(R.id.lay_show_wireless_pwd);
		final View layWirelessPwd = content.findViewById(R.id.lay_wireless_pwd);
		final EditText edWirelessPwd = (EditText) content.findViewById(R.id.ed_wireless_pwd);
		layShowWirelessPwd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				boolean isShow = view.getTag() == null ? false : Boolean.parseBoolean(view.getTag().toString());
				view.setTag(!isShow);
				imgShowWirelessPwd.setImageResource(isShow ? R.drawable.ob_eay_selected : R.drawable.ob_eay);
				edWirelessPwd.setInputType(InputType.TYPE_CLASS_TEXT
						| (isShow ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_TEXT_VARIATION_PASSWORD));
				edWirelessPwd.setSelection(edWirelessPwd.getText().toString().length());
			}
		});
		edWirelessPwd.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				layWirelessPwd.setBackgroundResource(hasFocus ? R.drawable.ob_border_n_ff00aef1 : R.drawable.ob_border_n_ffe1e1e1);
			}
		});
		dlgWirelessConnect = dialogUtil.create(content, true, true).setNoTitle().setConfirmListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String SSID = wifiInfo.getSSID();
				String ENCRYPT = wifiInfo.getENCRYPT();
				String PWD = edWirelessPwd.getText().toString().trim();

				showLoadingDialog(R.string.ob_wait_set_wifi_mode_1);
				if (dlgWirelessConnect != null) {
					dlgWirelessConnect.dismiss();
				}

				requestWirelessConnect(SSID, PWD, ENCRYPT);
			}
		}).finish();
		final Button btnWirelessConnect = dialogUtil.getConfirmButton();
		btnWirelessConnect.setText(R.string.ob_connect);
		btnWirelessConnect.setEnabled(false);
		edWirelessPwd.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				btnWirelessConnect.setEnabled(edWirelessPwd.getText().toString().trim().length() >= 8);
			}
		});
		txWirelessName.setText(wifiInfo.getSSID());
		dlgWirelessConnect.show();
	}

	private BaseAdapter wifiInfoAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			WifiSSIDList wifiInfo = wifiInfoList.get(position);
			View view;
			Viewactivity viewactivity;
			if (convertView == null) {
				viewactivity = new Viewactivity();
				view = LayoutInflater.from(holder).inflate(R.layout.ob_list_content_surf_settings_wifi_info, null);
				viewactivity.txSsid = (TextView) view.findViewById(R.id.tx_ssid);
				viewactivity.imgPower = (ImageView) view.findViewById(R.id.img_power);
				viewactivity.imgLock = (ImageView) view.findViewById(R.id.img_lock);
				view.setTag(viewactivity);
			} else {
				view = convertView;
				viewactivity = (Viewactivity) view.getTag();
			}
			viewactivity.imgPower.setImageLevel(wifiInfo.getMyLevel());
			viewactivity.imgLock.setVisibility(wifiInfo.isSecurity() ? View.VISIBLE : View.GONE);
			viewactivity.txSsid.setText(wifiInfo.getSSID());
			return view;
		}

		class Viewactivity {
			TextView txSsid;
			ImageView imgPower;
			ImageView imgLock;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return wifiInfoList.get(position);
		}

		@Override
		public int getCount() {
			return wifiInfoList.size();
		}
	};

	private void showLoadingDialog(int title) {
		dlgLoading = dialogUtil.createLoading(title, false, true).show();
	}

}
